package com.orange.cetback.handler;


import com.orange.cetback.common.constant.MessageConstant;
import com.orange.cetback.common.exception.BaseException;
import com.orange.cetback.common.exception.SiliconFlowException;
import com.orange.cetback.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result<String> exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.fail(ex.getMessage());
    }

    @ExceptionHandler
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info("");
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username=split[2];
            String msg=username+ MessageConstant.ALREADY_EXISTS;
            return Result.fail(msg);
        }else {
            return Result.fail(MessageConstant.UNKNOWN_ERROR);
        }

    }

    // 在GlobalExceptionHandler中添加
    @ExceptionHandler(SiliconFlowException.class)
    public Result<String> handleSiliconFlowException(SiliconFlowException ex) {
        log.error("硅基接口异常: {}", ex.getMessage());
        return Result.fail("对话服务暂时不可用，请稍后再试");
    }


}
